import { IEntityDetail, IParam } from '@/core/interface';
import Dexie, { Version } from 'dexie';

/**
 * 库实例基类
 *
 * @export
 * @class DBService
 * @extends {Dexie}
 */
export class DBService extends Dexie {
	/**
	 * 版本号
	 *
	 * @protected
	 * @type {Version}
	 * @memberof DBService
	 */
	protected v: Version;

	/**
	 * Creates an instance of DBService.
	 */
	constructor() {
		const environment = App.getEnvironment();
		const dbName = environment
			? `${environment.SysName}_${environment.AppName}_DefaultDB`
			: 'DefaultDB';
		super(dbName);
		this.v = this.version(1);
		this.init();
	}

	/**
	 * 唯一实例
	 *
	 * @protected
	 * @static
	 */
	protected static instance: DBService;

	/**
	 * 获取实例
	 *
	 * @static
	 * @return {*}  {DBService}
	 */
	static getInstance(): DBService {
		if (!this.instance) {
			this.instance = new DBService();
		}
		return this.instance;
	}

	/**
	 * 数据库初始化
	 *
	 * @protected
	 */
	protected init(): void {
		const table: IParam = {};
		const entityDetails = App.getAppEntityConfig();
		if (entityDetails && entityDetails.length > 0) {
			entityDetails.forEach((detail: IEntityDetail) => {
				if (detail.storageMode === 1) {
					Object.assign(table, {
						[detail.codeName.toLowerCase()]: `&${detail.keyField.toLowerCase()}`,
					});
				}
			});
		}
		this.v = this.v.stores(table);
	}
}
